<template>
  <el-dialog :close-on-click-modal="false" title="学校管理" width="80%"
             draggable v-model="visible">

    <el-tabs tab-position="top" editable v-model:model-value="data.activeName"
             @tabChange="getList"  @edit="handleTabsEdit">
      <template #add-icon> <el-button type="primary" @click="gradeFormRef.openDialog(data.schoolId,null)" >新增</el-button></template>
      <el-tab-pane v-for="item in data.gradeList"  :label="item.gradeName" :name="item.id">
        <template #label>
          <div class="tab-content">
            <span>{{item.gradeName}}</span>
            <el-icon @click="gradeFormRef.openDialog(item.schoolId,item.id)"><EditPen /></el-icon>
          </div>

        </template>
            <el-row>
              <div class="mb8" style="width: 100%">
                <el-button icon="folder-add" type="primary" class="ml10" @click="classesFormRef.openDialog(data.schoolId,data.activeName,null)" v-auth="'tb_classes_add'">
                 新增班级
                </el-button>
                <el-button plain :disabled="multiple" icon="Delete" type="primary" class="ml10" v-auth="'tb_classes_del'" @click="handleDelete(selectObjs)">
                  {{ $t('common.delBtn') }}
                </el-button>
                <right-toolbar
                    v-model:showSearch="showSearch"
                    :export="'sys_role_export'"
                    @exportExcel="exportExcel"
                    class="ml10"
                    style="float: right; margin-right: 20px"
                    @queryTable="getDataList"
                ></right-toolbar>
              </div>
            </el-row>
            <el-table
                :data="state.dataList"
                v-loading="state.loading"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                border
                :cell-style="tableStyle.cellStyle"
                :header-cell-style="tableStyle.headerCellStyle"
            >
              <el-table-column type="selection" :selectable="handleSelectable" width="50" align="center" />
              <el-table-column type="index" label="#" width="80" />
              <el-table-column prop="classesName" label="班级名称" show-overflow-tooltip></el-table-column>
              <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>
              <el-table-column prop="updateTime" label="修改时间" show-overflow-tooltip></el-table-column>
              <el-table-column :label="$t('common.action')" width="250">
                <template #default="scope">
                  <el-button text type="primary" icon="edit-pen" v-auth="'tb_classes_edit'" @click="classesFormRef.openDialog(data.schoolId,data.activeName,scope.row.id)">{{
                      $t('common.editBtn')
                    }}</el-button>

                  <el-tooltip :content="$t('sysrole.deleteDisabledTip')" :disabled="scope.row.roleId !== '1'" placement="top">
							<span style="margin-left: 12px">
								<el-button
                    text
                    type="primary"
                    icon="delete"
                    :disabled="scope.row.roleId === '1'"
                    v-auth="'tb_classes_del'"
                    @click="handleDelete([scope.row.id])"
                >{{ $t('common.delBtn') }}
								</el-button>
							</span>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
            <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />


      </el-tab-pane>

    </el-tabs>
    <grade-form ref="gradeFormRef" @refresh="getList"/>
    <classes-form ref="classesFormRef" @refresh="getDataList"/>
  </el-dialog>
</template>

<script lang="ts" name="systemRoleDialog" setup>
import {useMessage, useMessageBox} from '/src/hooks/message';
import {EditPen} from '@element-plus/icons-vue'
import {useI18n} from 'vue-i18n';
import {ElMessage, ElMessageBox, TabPaneName} from "element-plus";
import { BasicTableProps, useTable } from '/src/hooks/table';

import {listAll as listAllGrade,delObj as delGrade} from '/src/api/school/grade';
import {pageList,delObj as delClasses } from "/@/api/school/classes";

const GradeForm = defineAsyncComponent(() => import('./gradeForm.vue'))
const ClassesForm = defineAsyncComponent(() => import('./classesForm.vue'))
const showSearch = ref(true);

const {t} = useI18n();

// 定义变量内容
const gradeFormRef = ref();
const classesFormRef = ref();
const visible = ref(false);
// 多选rows
const selectObjs = ref([]) as any;
// 是否可以多选
const multiple = ref(true);
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    schoolId: '',
    gradeId: ''
  },
  pageList: pageList, // H
  asc: ['create_time'],
});
// 提交表单数据
const data = reactive({
  schoolId: '',
  gradeList: [],
  activeName: null
})
//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  data.schoolId = '';

  // 获取角色信息
  if (id) {
    data.schoolId = id;
    getList();
  }

};



// 清空搜索条件
const resetQuery = () => {
  queryRef.value.resetFields();
  getDataList();
};


const getList = async () => {
  const resp = await listAllGrade({schoolId: data.schoolId})
  data.gradeList = resp.data
  if(!data.activeName){
    data.activeName = resp.data[0].id
  }
  state.queryForm.schoolId = data.schoolId
  state.queryForm.gradeId = data.activeName
  getDataList();
}


// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 是否可以多选
const handleSelectable = (row: any) => {
  return row.roleId !== '1';
};

const handleTabsEdit = (targetName: TabPaneName | undefined,
                        action: 'remove' | 'add') => {
  if (action === 'add') {
    gradeFormRef.value.openDialog(data.schoolId,null)
    return;
  }
  if (action === 'remove') {
    ElMessageBox.confirm(
        `确认删除吗?`
    ).then( async() => {
      await delGrade([targetName]);
      ElMessage.success("删除成功")
      getList()
    })
    return;
  }
}

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch {
    return;
  }

  try {
    await delClasses(ids);
    getDataList();
    useMessage().success(t('common.delSuccessText'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};


// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
.tab-content{
  display: flex;
  align-content: center;
  justify-content: center;
  align-items: center;
  gap: 5px;
}
</style>
